/**
 * Project Name:Micro-Services-Common
 * File Name   :LoggerFactory.java
 * Package Name:com.micro.services.common.logger
 * Date:2015年9月8日上午12:20:59
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
*/

package com.micro.services.common.logger;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.micro.services.common.logger.jdk.JdkLoggerAdapter;
import com.micro.services.common.logger.slf4j.Slf4jLoggerAdapter;
import com.micro.services.common.logger.support.MicroServicesLogger;

/**
 * ClassName:LoggerFactory <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason :TODO ADD REASON. <br/>
 * Date :2015年9月8日 上午12:20:59 <br/>
 * 
 * @author :http://my.oschina.net/httpssl
 * @email :491835898@QQ.COM
 * @since :JDK 1.7
 * @see
 */
public final class LoggerFactory
{
	public static String RPC_LOG_PATTERN = "#application#-#service#-#method#-#[args]#-#[return]#";

	private static volatile LoggerAdapter							LOGGER_ADAPTER;
	/**
	 * Key 就是类名
	 * 
	 */
	private static final ConcurrentMap<String, MicroServicesLogger>	LOGGERS	= new ConcurrentHashMap<String, MicroServicesLogger>();

	/*
	 * 注入系统中定义的Logger..
	 */
	static {
		String logger = System.getProperty("micro.services.application.logger");
		if ("slf4j".equals(logger)) {
			setLoggerAdapter(new Slf4jLoggerAdapter());
		} else if ("jdk".equals(logger)) {
			setLoggerAdapter(new JdkLoggerAdapter());
		} else {
			try {
				setLoggerAdapter(new Slf4jLoggerAdapter());
			} catch (Throwable e1) {
				try {
					setLoggerAdapter(new JdkLoggerAdapter());
				} catch (Throwable e2) {
				}
			}
		}
	}

	/*
	 * 切换日志框架时,就会调用这个方法
	 */
	public static void setLoggerAdapter(LoggerAdapter loggerAdapter) {
		// TODO Auto-generated method stub
		if (loggerAdapter != null) {
			Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName());
			LoggerFactory.LOGGER_ADAPTER = loggerAdapter;
			for (Map.Entry<String, MicroServicesLogger> entry : LOGGERS.entrySet()) {
				entry.getValue().setLogger(logger);
			}
		}
	}

	public static Logger getLogger(Class<?> clazz) {
		MicroServicesLogger logger = LOGGERS.get(clazz.getName());
		if (logger == null) {
			LOGGERS.putIfAbsent(clazz.getName(),
					new MicroServicesLogger(LoggerFactory.LOGGER_ADAPTER.getLogger(clazz)));
		}
		return null;
	}

	/**
	 * 动态设置输出日志级别
	 * 
	 * @param level
	 *            日志级别
	 */
	public static void setLevel(Level level) {
		LOGGER_ADAPTER.setLevel(level);
	}

	/**
	 * 获取日志级别
	 * 
	 * @return 日志级别
	 */
	public static Level getLevel() {
		return LOGGER_ADAPTER.getLevel();
	}

	/**
	 * 获取日志文件
	 * 
	 * @return 日志文件
	 */
	public static File getFile() {
		return LOGGER_ADAPTER.getFile();
	}
	
}
